import { expect } from '@jest/globals';
import path from 'path';

import { addOhPackageDps, buildOneHapAndCheckFile, commonFileOperation, readZipEntry } from '../../plugins/common-fun';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  IsEnable,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility
  },
  modulesOption: [ModuleTemplateType.StaticLibraryWithC]
};

const testFun: TestCaseFun = async (project, taskConfig, record) => {
  // 1. 使entry依赖staticNativeCLibrary
  const entryPath = project.getModule('entry').moduleRootPath();
  await addOhPackageDps(entryPath, {
    'staticNativeCLibrary': '../staticNativeCLibrary'
  });

  // 2. 在entry模块的index.ets文件中进行ets components引用
  await commonFileOperation(path.resolve(entryPath, 'src/main/ets/pages/Index.ets'), async (buffer) => {
    let content = buffer.toString();
    content = content.replace('Text(this.message)', 'MainPage()\n        Text(this.message)');
    return `import { MainPage } from 'staticNativeCLibrary'\n\n ${content}`;
  });

  // 3. 构建entry模块
  await buildOneHapAndCheckFile('entry')(project, taskConfig, record);

  // 4. 查看hap包中index.ets文件中引用情况
  // eslint-disable-next-line max-len
  const content = await readZipEntry(path.resolve(entryPath, 'build/default/outputs/default/entry-default-unsigned.hap'), 'ets/sourceMaps.map');
  expect(content).toContain('staticNativeCLibrary/src/main/ets/components/mainpage/MainPage.ets');
};

// 将demo测试用例注册到测试用例中心
TestCaseBuilder.builder()
  .caseName('OPENLAB_AIDE_ZOS_Build_library_Dependence_HOS_api10_STAGE_001')
  .description('001、eTS工程，entry模块依赖ets+cpp共享模块_ets引用')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.L1).ohpmInstall(IsEnable.Enable).build())
  .testFun(testFun)
  .load();
